//
//  ViewController.m
//  Demo1-NSThread-Create
//
//  Created by LZXuan on 15-7-29.
//  Copyright (c) 2015年 轩哥. All rights reserved.
//

#import "ViewController.h"
#define kScreenSize [UIScreen mainScreen].bounds.size

#define kPrintThread NSLog(@"isMain:%d -func:%s",[NSThread isMainThread],__func__)

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSArray *arr = @[@"创建线程1",@"创建线程2",@"创建线程3"];
    for (NSInteger i = 0; i < arr.count; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        CGFloat space = 10;
        button.frame = CGRectMake(space, 100+30*i, kScreenSize.width-2*space, 30);
        [button setTitle:arr[i] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 101+i;
        [self.view addSubview:button];
    }
    kPrintThread;
}
- (void)btnClick:(UIButton *)button {
    kPrintThread;
    switch (button.tag) {
        case 101:
        {
            //第一种 创建后台线程
            //performSelectorInBackground内部会创建一个线程 专门 执行调用 -thread1Click:
            [self performSelectorInBackground:@selector(thread1Click:) withObject:@"线程1"];
        }
            break;
        case 102:
        {
            //第二种形式创建thread
            //创建一个线程 执行调用 -thread2Click:  、 object:就是前面函数的参数
            NSThread *thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(thread2Click:) object:@"线程2"];
            //设置名字
            thread2.name = @"thread2";
            //启动线程
            [thread2 start];//这种方式创建线程 需要手动启动
            
        }
            break;
        case 103:
        {
            //第3种创建 thread
            //一旦创建 线程会立即 执行调用
            [NSThread detachNewThreadSelector:@selector(thread3Click:) toTarget:self withObject:@"线程3"];
            
        }
            break;
            
        default:
            break;
    }
}
- (void)thread3Click:(id)obj {
    NSLog(@"obj:%@",obj);
    kPrintThread;
}

- (void)thread2Click:(id)obj {
    kPrintThread;
    NSLog(@"thread2:%@",[NSThread currentThread]);
    for (NSInteger i = 0; i < 20; i++) {
        NSLog(@"i = %ld",i);
        [NSThread sleepForTimeInterval:0.2];
    }
    NSLog(@"thread2 即将结束");
    //当前函数执行完 子线程就结束了
}

- (void)thread1Click:(id)obj {
    NSLog(@"obj:%@",obj);
    NSLog(@"thread:%@",[NSThread currentThread]);//获取当前线程
    kPrintThread;
    //NSLog(@"isMain:%d -func:%s",[NSThread isMainThread],__func__);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end





